<template>
	<div class="sys-container">
		<el-dialog v-model="state.isShowDialog" draggable width="769px">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit />
					</el-icon>
					<span> {{ props.title }} </span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" size="default" label-width="100px"
				:disabled="disabled.fromDisabled">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="媒体名称" prop='mediaId'
							:rules="[{ required: true, message: '媒体名称不能为空', trigger: 'blur' }]">
							<el-select v-model.trim="state.selectedMedia" placeholder="请选择" value-key="value"
								@change="handleChange" :disabled="disabled.editMedia" class="w100">
								<el-option v-for='item in state.mediaDict' :key='item.value' :label='item.label'
									:value='item' />
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="页面类型" prop='mediaPositionId'>
							<el-select v-model.trim="state.ruleForm.pageType" value-key="value" placeholder="请选择"
								class="w100" :disabled="disabled.editMedia">
								<el-option v-for='item in optionDict.promotionPage' :key='item.value'
									:label='item.label' :value='item.value' />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="产品名称">
							<el-select v-model.trim="state.customer" placeholder="官方（报备）页必选" value-key="value"
								:disabled="disabled.editMedia" class="w100" filterable>
								<el-option v-for='item in state.mediaCustomer' :key='item.value' :label='item.label'
									:value='item' />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="媒体业务" prop='mediaPositionId'>
							<el-select v-model.trim="state.ruleForm.businessId" value-key="value" placeholder="请选择"
								class="w100" :disabled="disabled.editMedia">
								<el-option v-for='item in state.mediaBusiness' :key='item.value' :label='item.label'
									:value='item.value' />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="代理资源" prop='mediaPositionId'
							:rules="[{ required: true, message: '媒体资源不能为空', trigger: 'blur' }]">
							<el-select v-model.trim="state.selectedMediaPosition" value-key="value" placeholder="请选择"
								class="w100" @change="handleChange" :disabled="disabled.editMedia">
								<el-option v-for='item in state.mediaPositionDict' :key='item.value' :label='item.label'
									:value='item' />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="触点编码" prop="code"
							:rules="[{ required: true, message: '触点编码不能为空', trigger: 'blur' }]">
							<el-input v-model.trim="state.ruleForm.code" placeholder="触点编码" maxlength='6' clearable
								@input='handleChange' :disabled="disabled.editMedia" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="状态">
							<el-select v-model.trim="state.ruleForm.status" placeholder="请选择" class="w100">
								<el-option label="启用" :value="1"></el-option>
								<el-option label="停用" :value="2"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="黑名单APP">
							<el-select v-model.trim="state.ruleForm.blackApp" placeholder="是否添加黑名单手机号" class="w100">
								<el-option label="未修改" :value="-1"></el-option>
								<el-option label="是" :value="1"></el-option>
								<el-option label="否" :value="2" ></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="短信回填">
							<el-select v-model.trim="state.ruleForm.appendVerifyCode" placeholder="是否记录短信验证码回填"
								class="w100">
								<el-option label="是" :value="1"></el-option>
								<el-option label="否" :value="0"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="扣除分子">
							<el-input-number v-model.trim="state.ruleForm.deductionNumerator" placeholder="扣除分子"
								class="w100" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="扣除分母">
							<el-input-number v-model.trim="state.ruleForm.deductionDenominator" placeholder="扣除分母"
								class="w100" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="克隆PID">
							<el-select v-model.trim="state.ruleForm.FromCloneMediaToucherId" value-key="value"
								placeholder="请选择" class="w100" allow-create filterable :disabled="disabled.editMedia">
								<el-option v-for='item in state.mediaToucherDict' :key='item.value' :label='item.label'
									:value='item.value' />
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="推广链接" prop="promotionLink"
							:rules="[{ required: true, message: '媒体名称不能为空', trigger: 'blur' }]">
							<el-input v-model.trim="state.ruleForm.promotionLink" placeholder="请输入推广链接内容" clearable
								type="textarea" :autosize="{ minRows: 2 }" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="代码分支">
							<el-input v-model.trim="state.ruleForm.programBranch" placeholder="请输入代码分支" clearable
								type="textarea" :autosize="{ minRows: 2 }" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="备注">
							<el-input v-model.trim="state.ruleForm.remark" placeholder="请输入备注内容" clearable
								type="textarea" :autosize="{ minRows: 2 }" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel" size="default">取 消</el-button>
					<el-button type="primary" @click="submit" size="default" v-show="!disabled.fromDisabled"
						:loading='state.load'>确
						定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup name="editDiMediaToucher">
import { reactive, ref } from 'vue';
import mittBus from '/@/utils/mitt';
import { optionDict } from '/@/const/dict';
import { DiMediaToucher } from '/@/api/models';
import SysDiMediaApi from '/@/api/delivery/media';
import SysDiMediaPositionApi from '/@/api/delivery/mediaPosition';
import SysDiMediaToucherApi from '/@/api/delivery/mediaToucher';
import SysDiBusinessApi from '/@/api/delivery/business';
import { ElMessage } from 'element-plus';
import apiCustomerProduct from "/@/api/delivery/customerProduct/index";
import commonFunction from '/@/utils/commonFunction';

// 定义变量内容
const { generateRandomLowercaseNumber } = commonFunction();

const props = defineProps({
	title: String,
});

const ruleFormRef = ref();
const state = reactive({
	selectedMedia: null,
	selectedMediaPosition: null,
	mediaDict: [],
	mediaPositionDict: [],
	isShowDialog: false,
	ruleForm: {} as DiMediaToucher,
	mediaBusiness: [],
	mediaToucherDict: [],
	mediaCustomer: [],
	customer: [],
	product: '',
	load: false,
});
let disabled = reactive({
	fromDisabled: false,
	editMedia: true
});

// 打开弹窗
const openDialog = async (row: DiMediaToucher, ages: string | null) => {
	disabled.fromDisabled = false;
	disabled.editMedia = false;
	state.product = row.productId;
	// console.log(row, 'rw');

	if (ages == 'details') disabled.fromDisabled = true;
	if (ages == 'edit') disabled.editMedia = true;
	if (ages == 'edit') disabled.editMedia = true;

	await mediaDictQuery();
	state.selectedMedia = state.mediaDict.find((item) => {
		return item.value === row.mediaId;
	}) ?? null;
	await mediaPositionDictQuery();
	state.selectedMediaPosition = state.mediaPositionDict.find((item) => {
		return item.value === row.mediaPositionId;
	}) ?? null;
	await mediaDiBusinessQuery()
	await mediaToucherDictQuery();
	await mediaapiCustomerProductQuery();
	state.ruleForm = row;
	state.isShowDialog = true;
	state.customer = [];
	state.mediaCustomer.forEach(item => {
		if (item.value == row.productId) {
			state.customer = item.label;
			// console.log(state.customer);
		}
	})
	if (ages == 'add') state.ruleForm.code = generateRandomLowercaseNumber(6);

};

// 关闭弹窗
const closeDialog = () => {
	mittBus.emit('submitRefresh');
	state.selectedMedia = null;
	state.selectedMediaPosition = null;
	state.isShowDialog = false;
};

// 取消
const cancel = () => {
	state.selectedMedia = null;
	state.selectedMediaPosition = null;
	state.isShowDialog = false;
};

// 提交
const submit = () => {
	state.load = true;
	state.ruleForm.mediaId = state.selectedMedia?.value;
	state.ruleForm.mediaCode = state.selectedMedia?.exValue;
	state.ruleForm.mediaPositionId = state.selectedMediaPosition?.value;
	state.ruleForm.mediaPositionCode = state.selectedMediaPosition?.exValue;
	// state.ruleForm.customerId = state.customer?.exValueData;

	// console.log(state.customer,'sss');

	ruleFormRef.value.validate(async (valid: boolean) => {
		if (!valid) return;
		let res;
		if (state.ruleForm.id != undefined && state.ruleForm.id > 0) {
			state.ruleForm.productId = state.product;

			res = await SysDiMediaToucherApi().editPost(state.ruleForm);
		} else {

			state.ruleForm.customerId = state.customer.exValueData;
			state.ruleForm.productId = state.customer.value;
			res = await SysDiMediaToucherApi().addPost(state.ruleForm);
		}
		if (res.data.resCode != '0000')
			ElMessage.error(res.data.resMessage);
		else {
			ElMessage.success("操作成功");
			closeDialog();
		}

		state.load = false;


	});
};

// 媒体列表
const mediaDictQuery = async () => {
	await SysDiMediaApi().queryAll().then((res) => {
		if (res.data.resCode === '0000')
			state.mediaDict = res.data.result ?? [];
	});
};

// 代理资源列表
const mediaPositionDictQuery = async () => {
	await SysDiMediaPositionApi().queryAll().then((res) => {
		if (res.data.resCode === '0000')
			state.mediaPositionDict = res.data.result ?? [];
	});
};
// 媒体业务
const mediaDiBusinessQuery = async () => {
	await SysDiBusinessApi().queryAll().then((res) => {
		if (res.data.resCode === '0000')
			state.mediaBusiness = res.data.result ?? [];
	});
};

// 产品
const mediaapiCustomerProductQuery = async () => {
	await apiCustomerProduct().queryAll().then((res) => {
		if (res.data.resCode === '0000')
			state.mediaCustomer = res.data.result ?? [];
	});
};

const handleChange = (val: number) => {
	if (props.title === "添加") {
		if (state.selectedMedia.label == '头条') {
			state.ruleForm.promotionLink = "https://vrbt.qimingwenhua.net/"
				+ state.selectedMedia?.exValue + "_" + state.selectedMediaPosition?.exValue + "_" + state.ruleForm.code + "/" + "?ua=__UA__&union_site=__UNION_SITE__"
		} else {
			state.ruleForm.promotionLink = "https://vrbt.qimingwenhua.net/"
				+ state.selectedMedia?.exValue + "_" + state.selectedMediaPosition?.exValue + "_" + state.ruleForm.code + "/"
		}
	}
};

// 媒体触点列表
const mediaToucherDictQuery = async () => {
	await SysDiMediaToucherApi().queryAll({ status: 1 }).then((res) => {
		if (res.data.resCode === '0000')
			state.mediaToucherDict = res.data.result ?? [];
	});
};

/*

*/

// 导出对象
defineExpose({ openDialog });
</script>
